/**
 * 文件上传相关API
 */
import request from '@/utils/request';

/**
 * 上传文件
 * @param file 文件对象
 * @param folder 文件夹名称
 * @param onProgress 上传进度回调
 * @returns Promise<any>
 */
export const uploadFile = (
  file: File, 
  folder: string = 'uploads',
  onProgress?: (progress: number) => void
) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('folder', folder);
  
  return request.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(progress);
      }
    }
  });
};

/**
 * 批量上传文件
 * @param files 文件数组
 * @param folder 文件夹名称
 * @param onProgress 上传进度回调
 * @returns Promise<any[]>
 */
export const uploadFiles = async (
  files: File[],
  folder: string = 'uploads',
  onProgress?: (progress: number) => void
) => {
  const uploadPromises = files.map(file => uploadFile(file, folder, onProgress));
  return Promise.all(uploadPromises);
};

/**
 * 删除文件
 * @param fileId 文件ID
 * @returns Promise<any>
 */
export const deleteFile = (fileId: string) => {
  return request.delete(`/upload/${fileId}`);
};

/**
 * 获取文件列表
 * @param folder 文件夹名称
 * @returns Promise<any>
 */
export const getFileList = (folder?: string) => {
  const params = folder ? { folder } : {};
  return request.get('/upload/list', { params });
};

/**
 * 下载文件
 * @param fileId 文件ID
 * @param fileName 文件名
 * @returns Promise<any>
 */
export const downloadFile = (fileId: string, fileName: string) => {
  return request.get(`/upload/download/${fileId}`, {
    responseType: 'blob'
  }).then(response => {
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  });
};
